<template>
  <div>
    <el-form ref="formRef" :model="form" label-width="80px" inline class="search-form">
      <el-form-item
        v-for="item in formData.list"
        :key="item.model"
        :prop="item.model"
      >
        <el-input
          v-if="item.type === 'input'"
          v-model="form[item.model]"
          clearable
          :placeholder="item.placeholder"
        />
        <el-select v-if="item.type === 'select'" v-model="form[item.model]" clearable :placeholder="item.placeholder">
          <el-option
            v-for="(itemOp,index) in item.option"
            :key="index"
            :value="itemOp.value"
            :label="itemOp.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item class="query-action">

        <el-dropdown v-if="formData.downloadTemplateService" trigger="click" style="margin-right: 10px;">
          <el-button class="el-dropdown-link">
            导出<i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown" style="width:100px;text-align:center">
            <el-dropdown-item @click.native="handleDownload('all')"> 导出所有 </el-dropdown-item>
            <el-dropdown-item @click.native="handleDownload()"> 导出选中 </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button v-if="formData.downloadTemplateService" @click="handleImport">导入</el-button>

        <el-button @click="resetBtn"> 重置 </el-button>
        <el-button type="primary" @click="$emit('getTableData',form)"> 查询 </el-button>
        <el-button v-permission="[AddBut]" type="primary" @click="$emit('addBtn')"> 新增 </el-button>
        <el-button v-permission="[deleteButton]" :disabled="ids.length === 0" type="danger" @click="deleteBtn"> 删除 </el-button>
      </el-form-item>
    </el-form>

    <dtDialog
      title="导入"
      class="get-page-form-import-dialog"
      :visible.sync="fileUploadVisible"
      width="620px"
      :is-loading="uploadLoading"
      @closeDialog="fileUploadVisible = false"
      @comfirmBtn="importDataSave"
    >
      <el-form slot="content">
        <div class="">
          <dt-importFile ref="dtImportFileRef" :down-load-template="handleImportTemplate" :type="fileName" />
        </div>
      </el-form>
    </dtDialog>
  </div>
</template>

<script>
/**
 *  @param (Object) formData
 *  @param (Array) ids 删除时的ids
 *  formData[list] 需要使用的表单
 *  formData[MyButton] 需要使用的按钮
 *  formData[list]下的item 的 [model]： 传递的参数
 *  formData[list]下的item 的 [placeholder]： 传递的占位符
 *  formData[list]下的item 的 [type]： input 或 select
 *  formData[list]下的item 的 [option]： [type]位select时，传入的数据列表
 *  formData[list]下的item 的 [option]： [type]位select时，传入的数据列表
 *  formData[deleteAddress] 删除的地址
 *  formData[method] 删除接口的请求方式
 *  downloadTemplateService 下载模板
 *  exportAllService 导出所有数据
 *  ServiceExport 导出选中数据
 *  ServiceUpload 导入
 */
import { default as request, cloud } from '@/framework/utils/request'

export default {
  name: 'GetPageForm',
  props: {
    formData: {
      type: Object
    },
    ids: {
      type: Array
    },
    AddBut: {
      type: String
    },
    SeaBut: {
      type: String
    },
    deleteButton: {
      type: String
    }
  },
  data() {
    return {
      form: {},
      fileName: '服务器监控数据导入',
      handleImportTemplate: this.formData.downloadTemplateService,
      fileUploadVisible: false,
      uploadLoading: false
    }
  },
  methods: {

    // 上传文件
    importDataSave() {
      const file = this.$refs.dtImportFileRef.fileList
      if (file.length == 0) {
        this.$dtMessage({
          title: '失败',
          message: '请选择需要上传的文件',
          type: 'error',
          duration: 2000
        })
        return
      }
      const formData = new FormData()
      // 数据
      formData.append('file', file[0].raw)
      formData.append('name', file[0].name)
      this.uploadLoading = true
      this.formData.ServiceUpload(formData).then(async(res) => {
        this.fileUploadVisible = false
        if (res.errorDownloadPath) {
          this.$alert('<div> <div class="title">' + res.tip + '</div> <div class="content"><span class="btn" id="messageBtn" style="color:#5688E8;cursor:pointer">点击下载导入失败用户信息</span> </div> </div>', '导入完成', {
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$alert('<div> <div class="title">' + res.tip + '导入完成', {
            dangerouslyUseHTMLString: true
          })
        }
        // this.$message.success('导入成功')
        this.$emit('getTableData')
        await this.$nextTick()
        document.getElementById('messageBtn').onclick = function() {
          window.location.href = res.errorDownloadPath
        }
      }).finally(res => {
        this.uploadLoading = false
      })
    },

    async handleImport() {
      this.fileUploadVisible = true
      await this.$nextTick()
      this.$refs.dtImportFileRef.fileList = []
    },

    handleDownload(type) {
      if (type == 'all') {
        this.showScreenLoading()
        this.formData.exportAllService().then(res => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          a.download = '服务器状态监控全部导出' // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.hideScreenLoading()
        }).catch(res => {
          this.hideScreenLoading()
        })
      } else {
        if (!this.ids || this.ids.length === 0) {
          this.$dtMessage({
            title: '失败',
            message: '请至少选择一项',
            type: 'error',
            duration: 2000
          })
          return
        }
        const con = {
          serverMonitorIds: this.ids.join(',')
        }
        this.showScreenLoading()
        this.formData.ServiceExport(con).then(res => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          a.download = '服务器状态监控部分导出' // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.hideScreenLoading()
        }).catch(res => {
          this.hideScreenLoading()
        })
      }
    },

    resetBtn() {
      this.form = {}
      this.$emit('resetBtn', false)
    },
    deleteBtn() {
      this.$confirm('此操作将删除数据, 是否继续?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = await request({
          url: cloud.interfacePlatform + this.formData.deleteAddress,
          method: this.formData.method,
          data: { ids: this.ids }
        })
        if (data.code === '00000') {
          this.$message.success('删除成功')
          this.$emit('getTableData', this.form)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep.get-page-form-import-dialog {
  .el-upload-list__item {
    transition: none !important;
  }
  .el-upload-list__item-name {
    transition: none !important;
  }
}
</style>
